package com.ajing.logextractor.config;

import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.representer.Representer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

@Slf4j
public class YamlConfigLoader {

    private static final String CONFIG_FILE_NAME = "log-extractor%s.yaml";
    private static final String CONFIG_DIR_PATH = "./config";
    private static ConsumerConfig consumerConfig = new ConsumerConfig();

    static {
        String configFileName = String.format(CONFIG_FILE_NAME, "");
        InputStream inputStream = null;
        try {
            Representer representer = new Representer(new DumperOptions());
            String active = System.getProperty("active");
            if (null != active && active.length() > 0) {
                active = "-" + active;
            } else {
                active = "";
            }
            representer.getPropertyUtils().setSkipMissingProperties(true);
            LoaderOptions loaderOptions = new LoaderOptions();
            Yaml yaml = new Yaml(new Constructor(ConsumerConfig.class, loaderOptions), representer);
            configFileName = String.format(CONFIG_FILE_NAME, active);
            log.info(String.format("Yaml load config from file: %s", configFileName));
            File file = new File(CONFIG_DIR_PATH + File.separator + configFileName);

            if (file.exists()) {
                inputStream = new FileInputStream(file);
            } else {
                inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(configFileName);
                if (null == inputStream) {
                    inputStream = YamlConfigLoader.class.getClassLoader().getResourceAsStream(configFileName);
                }
            }
            if (null != inputStream) {
                consumerConfig = yaml.loadAs(inputStream, ConsumerConfig.class);
            }
        } catch (FileNotFoundException e) {
            log.error("加载配置文件【" + configFileName + "】失败", e);
            throw new RuntimeException("加载配置文件【" + configFileName + "】失败");
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    log.error("关闭文件流失败", e);
                }
            }
        }
    }


    public static ConsumerConfig getConfig() {
        return consumerConfig;
    }
}
